<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Websocket实现前后端实时通信 | Ther的小站</title><meta name="author" content="Ther"><meta name="copyright" content="Ther"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="WebSocket简介什么是websocket WebSocket 是一种网络通信协议。RFC6455定义了它的通信标准。 WebSocket是HTML5下一种新的协议（websocket协议本质上是一个基于tcp的协议） 它实现了浏览器与服务器全双工通信，能更好的节省服务器资源和带宽并达到实时通讯的目的 http是一种无状态，无连接，单向的应用层协议，它采用了请求&#x2F;响应模型，通信请">
<meta property="og:type" content="article">
<meta property="og:title" content="Websocket实现前后端实时通信">
<meta property="og:url" content="http://cjx_0723.gitee.io/2023/04/25/%E5%90%8E%E7%AB%AF/Java%E5%BC%80%E5%8F%91/Websocket%E5%AE%9E%E7%8E%B0%E5%89%8D%E5%90%8E%E7%AB%AF%E5%AE%9E%E6%97%B6%E9%80%9A%E4%BF%A1/index.html">
<meta property="og:site_name" content="Ther的小站">
<meta property="og:description" content="WebSocket简介什么是websocket WebSocket 是一种网络通信协议。RFC6455定义了它的通信标准。 WebSocket是HTML5下一种新的协议（websocket协议本质上是一个基于tcp的协议） 它实现了浏览器与服务器全双工通信，能更好的节省服务器资源和带宽并达到实时通讯的目的 http是一种无状态，无连接，单向的应用层协议，它采用了请求&#x2F;响应模型，通信请">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://w.wallhaven.cc/full/l8/wallhaven-l83o92.jpg">
<meta property="article:published_time" content="2023-04-25T10:31:38.028Z">
<meta property="article:modified_time" content="2023-05-11T14:12:05.221Z">
<meta property="article:author" content="Ther">
<meta property="article:tag" content="Java开发 Vue开发">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://w.wallhaven.cc/full/l8/wallhaven-l83o92.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://cjx_0723.gitee.io/2023/04/25/%E5%90%8E%E7%AB%AF/Java%E5%BC%80%E5%8F%91/Websocket%E5%AE%9E%E7%8E%B0%E5%89%8D%E5%90%8E%E7%AB%AF%E5%AE%9E%E6%97%B6%E9%80%9A%E4%BF%A1/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"YGMR4LH4DH","apiKey":"1fb48f3686d76eaf600890b7d3bb69c9","indexName":"index_hexo","hits":{"per_page":10},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#2d3035","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Websocket实现前后端实时通信',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-05-11 22:12:05'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="Ther的小站" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">31</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://w.wallhaven.cc/full/l8/wallhaven-l83o92.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Ther的小站"><span class="site-name">Ther的小站</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Websocket实现前后端实时通信</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-04-25T10:31:38.028Z" title="发表于 2023-04-25 18:31:38">2023-04-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-05-11T14:12:05.221Z" title="更新于 2023-05-11 22:12:05">2023-05-11</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%90%8E%E7%AB%AF/">后端</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Websocket实现前后端实时通信"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><meta name="referrer" content="no-referrer"/>

<h1 id="WebSocket简介"><a href="#WebSocket简介" class="headerlink" title="WebSocket简介"></a>WebSocket简介</h1><h3 id="什么是websocket"><a href="#什么是websocket" class="headerlink" title="什么是websocket"></a>什么是<a target="_blank" rel="noopener" href="https://so.csdn.net/so/search?q=websocket&spm=1001.2101.3001.7020">websocket</a></h3><ul>
<li>WebSocket 是一种网络通信协议。RFC6455定义了它的通信标准。</li>
<li>WebSocket是HTML5下一种新的协议（websocket协议本质上是一个基于tcp的协议）</li>
<li>它实现了浏览器与服务器<a target="_blank" rel="noopener" href="https://so.csdn.net/so/search?q=%E5%85%A8%E5%8F%8C%E5%B7%A5&spm=1001.2101.3001.7020">全双工</a>通信，能更好的节省服务器资源和带宽并达到实时通讯的目的</li>
<li>http是一种无状态，无连接，单向的<a target="_blank" rel="noopener" href="https://so.csdn.net/so/search?q=%E5%BA%94%E7%94%A8%E5%B1%82%E5%8D%8F%E8%AE%AE&spm=1001.2101.3001.7020">应用层协议</a>，它采用了请求&#x2F;响应模型，通信请求只能由客户端发起，服务端对请求做出应答处理。这样的弊端显然是很大的，只要服务端状态连续变化，客户端就必须实时响应，都是通过javascript与ajax进行轮询，这样显然是非常麻烦的，同时轮询的效率低，非常的浪费资源(http一直打开，一直重复的连接)。</li>
<li>于是就有了websocket，Websocket是一个持久化的协议，它是一种全面双工通讯的网络技术，任意一方都可以建立连接将数据推向另一方，websocket只需要建立一次连接，就可以一直保持</li>
</ul>
<h3 id="websocket-原理"><a href="#websocket-原理" class="headerlink" title="websocket 原理"></a>websocket 原理</h3><ul>
<li>websocket约定了一个通信的规范，通过一个握手的机制，客户端和服务器之间能建立一个类似tcp的连接，从而方便它们之间的通信</li>
<li>在websocket出现之前，web交互一般是基于http协议的短连接或者长连接</li>
<li>websocket是一种全新的协议，不属于http无状态协议，协议名为”ws”</li>
<li>说它是TCP传输，主要体现在建立长连接后，浏览器是可以给服务器发送数据，服务器也可以给浏览器发送请求的。当然它的数据格式并不是自己定义的，是在要传输的数据外层有ws协议规定的外层包的。</li>
</ul>
<h3 id="websocket与http的关系"><a href="#websocket与http的关系" class="headerlink" title="websocket与http的关系"></a>websocket与http的关系</h3><ul>
<li><strong>相同点：</strong></li>
<li><strong>都是基于tcp的，都是可靠性传输协议，都是应用层协议</strong></li>
<li><strong>不同点：</strong></li>
<li><strong>WebSocket是双向通信协议，模拟Socket协议，可以双向发送或接受信息</strong></li>
<li><strong>HTTP是单向的</strong></li>
<li><strong>WebSocket是需要浏览器和服务器握手进行建立连接的</strong></li>
<li><strong>而http是浏览器发起向服务器的连接，服务器预先并不知道这个连接</strong></li>
<li><strong>联系</strong></li>
<li><strong>WebSocket在建立握手时，数据是通过HTTP传输的。但是建立之后，在真正传输时候是不需要HTTP协议的</strong></li>
<li><strong>关系图</strong></li>
</ul>
<p><strong><img src="https://img-blog.csdnimg.cn/11cd72c1e9434dcda18a1dbf059f5fb1.png" alt="img"></strong></p>
<p><img src="https://img-blog.csdnimg.cn/ed6e4f8cf2ea4de7a33ccc282f18a0f1.png" alt="img"></p>
<h1 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h1><h2 id="后端代码"><a href="#后端代码" class="headerlink" title="后端代码"></a>后端代码</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.dce.blockchain.websocket;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.websocket.*;</span><br><span class="line"><span class="keyword">import</span> javax.websocket.server.PathParam;</span><br><span class="line"><span class="keyword">import</span> javax.websocket.server.ServerEndpoint;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.CopyOnWriteArraySet;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="comment">// 定义连接时候的 url</span></span><br><span class="line"><span class="meta">@ServerEndpoint(&quot;/websocket/&#123;key&#125;&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">WebSocketServer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//与某个客户端的连接会话，需要通过它来给客户端发送数据</span></span><br><span class="line">    <span class="keyword">private</span> Session session;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> CopyOnWriteArraySet&lt;WebSocketServer&gt; webSockets = <span class="keyword">new</span> <span class="title class_">CopyOnWriteArraySet</span>&lt;&gt;();</span><br><span class="line">    <span class="comment">//用来存放每个客户端对应的WebSocket对象。</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Map&lt;String, Session&gt; sessionPool = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 连接成功后调用的方法</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> session</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key key用来标记一个对话，一个对话对应一个key，key通过路径变量传递</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@OnOpen</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onOpen</span><span class="params">(Session session, <span class="meta">@PathParam(&quot;key&quot;)</span> String key)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">        <span class="comment">//key为前端传给后端的token</span></span><br><span class="line">        <span class="built_in">this</span>.session = session;</span><br><span class="line">        <span class="comment">// 从token中获取到userid当做区分websocket客户端的key</span></span><br><span class="line">        sessionPool.put(String.valueOf(key), session);</span><br><span class="line">        <span class="keyword">if</span> (sessionPool.get(String.valueOf(key)) == <span class="literal">null</span>) &#123;</span><br><span class="line">            webSockets.add(<span class="built_in">this</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        webSockets.add(<span class="built_in">this</span>);</span><br><span class="line">        log.info(<span class="string">&quot;webSocket连接成功&quot;</span>);</span><br><span class="line">        log.info(<span class="string">&quot;WebSocket有新的连接，连接总数为：&quot;</span> + webSockets.size());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 连接关闭调用的方法</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@OnClose</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onClose</span><span class="params">()</span> &#123;</span><br><span class="line">        webSockets.remove(<span class="built_in">this</span>);</span><br><span class="line">        log.info(<span class="string">&quot;webSocket连接关闭&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 收到客户端消息后调用的方法，根据业务要求进行处理，这里就简单地将收到的消息直接群发推送出去</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> message 客户端发送过来的消息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@OnMessage</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onMessage</span><span class="params">(String message)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;WebSocket收到客户端消息：&quot;</span> + message);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 发生错误时的回调函数</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> session</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> error</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@OnError</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onError</span><span class="params">(Session session, Throwable error)</span> &#123;</span><br><span class="line">        log.error(<span class="string">&quot;发生错误&quot;</span>);</span><br><span class="line">        error.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 单点消息发送</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 发送session 对应的key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> message</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">sendTextMessage</span><span class="params">(String key, String message)</span> &#123;</span><br><span class="line">        <span class="type">Session</span> <span class="variable">session</span> <span class="operator">=</span> sessionPool.get(key);</span><br><span class="line">        <span class="keyword">if</span> (session != <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                session.getBasicRemote().sendText(message);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="前端代码"><a href="#前端代码" class="headerlink" title="前端代码"></a>前端代码</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 提示信息</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="title class_">Message</span> &#125; <span class="keyword">from</span> <span class="string">&#x27;element-ui&#x27;</span></span><br><span class="line"><span class="comment">// 引入token 解析用户id在后端处理</span></span><br><span class="line"><span class="keyword">import</span> &#123; getToken &#125; <span class="keyword">from</span> <span class="string">&#x27;@/utils/auth&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 后端ip端口</span></span><br><span class="line"><span class="keyword">var</span> url = <span class="string">&#x27;ws://localhost:8090/websocket/&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> ws</span><br><span class="line"><span class="keyword">var</span> tt</span><br><span class="line"><span class="keyword">var</span> lockReconnect = <span class="literal">false</span> <span class="comment">// 避免重复连接</span></span><br><span class="line"><span class="keyword">var</span> clientId = <span class="title function_">getToken</span>() <span class="comment">// cookies中获取token值</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> websocket = &#123;</span><br><span class="line"><span class="comment">// 建立连接</span></span><br><span class="line">  <span class="title class_">Init</span>: <span class="keyword">function</span>(<span class="params">clientId</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="string">&#x27;WebSocket&#x27;</span> <span class="keyword">in</span> <span class="variable language_">window</span>) &#123;</span><br><span class="line">      ws = <span class="keyword">new</span> <span class="title class_">WebSocket</span>(url + clientId)</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">&#x27;MozWebSocket&#x27;</span> <span class="keyword">in</span> <span class="variable language_">window</span>) &#123;</span><br><span class="line">      ws = <span class="keyword">new</span> <span class="title class_">MozWebSocket</span>(url + clientId)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// console.log(&#x27;您的浏览器不支持 WebSocket!&#x27;)</span></span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// websocket 生命周期根据websocket状态自己会执行</span></span><br><span class="line">    <span class="comment">// websocket 成功 失败 错误 断开 这里会自动执行</span></span><br><span class="line">    <span class="comment">// 这个方法后端通过send调用 这个方法会执行和接收参数</span></span><br><span class="line">    ws.<span class="property">onmessage</span> = <span class="keyword">function</span>(<span class="params">e</span>) &#123;</span><br><span class="line">      <span class="comment">// console.log(&#x27;接收消息:&#x27; + e.data)</span></span><br><span class="line">      <span class="keyword">var</span> data = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(e.<span class="property">data</span>)</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(data)</span><br><span class="line">      heartCheck.<span class="title function_">start</span>()</span><br><span class="line">      <span class="keyword">if</span> (data.<span class="property">msg</span> !== <span class="string">&#x27;&#x27;</span> &amp;&amp; data.<span class="property">msg</span> !== <span class="literal">undefined</span>) &#123;</span><br><span class="line">        <span class="title class_">Message</span>(&#123;</span><br><span class="line">          <span class="attr">message</span>: e.<span class="property">data</span>.<span class="property">msg</span>,</span><br><span class="line">          <span class="attr">type</span>: <span class="string">&#x27;success&#x27;</span></span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// messageHandle(e.data)</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ws.<span class="property">onclose</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;连接已关闭&#x27;</span>)</span><br><span class="line">      <span class="title class_">Message</span>(&#123;</span><br><span class="line">        <span class="attr">message</span>: <span class="string">&#x27;webSocket连接已经关闭&#x27;</span>,</span><br><span class="line">        <span class="attr">type</span>: <span class="string">&#x27;error&#x27;</span></span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="title function_">reconnect</span>(clientId)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ws.<span class="property">onopen</span> = <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">      <span class="comment">// console.log(&#x27;连接成功&#x27;)</span></span><br><span class="line">      <span class="title class_">Message</span>(&#123;</span><br><span class="line">        <span class="attr">message</span>: <span class="string">&#x27;webSocket连接成功&#x27;</span>,</span><br><span class="line">        <span class="attr">type</span>: <span class="string">&#x27;success&#x27;</span></span><br><span class="line">      &#125;)</span><br><span class="line">      heartCheck.<span class="title function_">start</span>()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ws.<span class="property">onerror</span> = <span class="keyword">function</span>(<span class="params">e</span>) &#123;</span><br><span class="line">      <span class="comment">// console.log(&#x27;数据传输发生错误&#x27;)</span></span><br><span class="line">      <span class="title class_">Message</span>(&#123;</span><br><span class="line">        <span class="attr">message</span>: <span class="string">&#x27;数据传输发生错误&#x27;</span>,</span><br><span class="line">        <span class="attr">type</span>: <span class="string">&#x27;error&#x27;</span></span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="title function_">reconnect</span>(clientId)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 我们单独写了一个方法 调用ws的关闭方法，这样就可以在退出登录的时候主动关闭连接</span></span><br><span class="line">  <span class="comment">// 关闭连接</span></span><br><span class="line">  <span class="attr">onClose</span>: <span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;主动关闭连接！&#x27;</span>)</span><br><span class="line">    <span class="comment">// 关闭websocket连接和关闭断开重连机制</span></span><br><span class="line">    lockReconnect = <span class="literal">true</span></span><br><span class="line">    <span class="comment">// 调用 上面的websocket关闭方法</span></span><br><span class="line">    ws.<span class="title function_">close</span>()</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 前端的send给后端发信息</span></span><br><span class="line">  <span class="title class_">Send</span>: <span class="keyword">function</span>(<span class="params">sender, reception, body, flag</span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> data = &#123;</span><br><span class="line">      <span class="attr">sender</span>: sender,</span><br><span class="line">      <span class="attr">reception</span>: reception,</span><br><span class="line">      <span class="attr">body</span>: body,</span><br><span class="line">      <span class="attr">flag</span>: flag</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> msg = <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(data)</span><br><span class="line">    <span class="comment">// console.log(&#x27;发送消息：&#x27; + msg)</span></span><br><span class="line">    ws.<span class="title function_">send</span>(msg)</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 返回ws对象</span></span><br><span class="line">  <span class="title function_">getWebSocket</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> ws</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// websocket 自带的状态码意思提示</span></span><br><span class="line">  <span class="title function_">getStatus</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (ws.<span class="property">readyState</span> === <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&#x27;未连接&#x27;</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ws.<span class="property">readyState</span> === <span class="number">1</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&#x27;已连接&#x27;</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ws.<span class="property">readyState</span> === <span class="number">2</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&#x27;连接正在关闭&#x27;</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ws.<span class="property">readyState</span> === <span class="number">3</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&#x27;连接已关闭&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 刷新页面后需要重连</span></span><br><span class="line"><span class="keyword">if</span> (<span class="variable language_">window</span>.<span class="property">performance</span>.<span class="property">navigation</span>.<span class="property">type</span> === <span class="number">1</span> &amp;&amp; <span class="title function_">getToken</span>() != <span class="literal">null</span>) &#123;</span><br><span class="line">  <span class="comment">// 刷新后重连</span></span><br><span class="line">  <span class="comment">// reconnect(clientId);</span></span><br><span class="line">  websocket.<span class="title class_">Init</span>(clientId)</span><br><span class="line">  <span class="comment">// 如果websocket没连接成功，则开始延迟连接</span></span><br><span class="line">  <span class="keyword">if</span> (ws == <span class="literal">null</span>) &#123;</span><br><span class="line">    <span class="title function_">reconnect</span>(clientId)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> websocket</span><br><span class="line"></span><br><span class="line"><span class="comment">// 根据消息标识做不同的处理</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">messageHandle</span>(<span class="params">message</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> msg = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(message)</span><br><span class="line">  <span class="keyword">switch</span> (msg.<span class="property">flag</span>) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;command&#x27;</span>:</span><br><span class="line">      <span class="comment">// console.log(&#x27;指令消息类型&#x27;)</span></span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;inform&#x27;</span>:</span><br><span class="line">      <span class="comment">// console.log(&#x27;通知&#x27;)</span></span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">    <span class="comment">// console.log(&#x27;未知消息类型&#x27;)</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 重连方法 刷新页面 连接错误 连接关闭时调用</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">reconnect</span>(<span class="params">sname</span>) &#123;</span><br><span class="line">  <span class="keyword">if</span> (lockReconnect) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  lockReconnect = <span class="literal">true</span></span><br><span class="line">  <span class="comment">// 没连接上会一直重连，设置延迟避免请求过多</span></span><br><span class="line">  tt &amp;&amp; <span class="built_in">clearTimeout</span>(tt)</span><br><span class="line">  tt = <span class="built_in">setTimeout</span>(<span class="keyword">function</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// console.log(&#x27;执行断线重连...&#x27;)</span></span><br><span class="line">    websocket.<span class="title class_">Init</span>(sname)</span><br><span class="line">    lockReconnect = <span class="literal">false</span></span><br><span class="line">  &#125;, <span class="number">4000</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在需要使用的页面，编写下面的代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">     <span class="title function_">created</span>(<span class="params"></span>) &#123;</span><br><span class="line">          websocket.<span class="title class_">Init</span>(<span class="string">&#x27;mine&#x27;</span>)</span><br><span class="line">          <span class="keyword">var</span> wb = websocket.<span class="title function_">getWebSocket</span>()</span><br><span class="line">          wb.<span class="property">onmessage</span> = <span class="variable language_">this</span>.<span class="property">handleMessage</span></span><br><span class="line">     &#125;,</span><br><span class="line">     <span class="attr">methods</span>: &#123;</span><br><span class="line">          <span class="title function_">handleMessage</span>(<span class="params">e</span>) &#123;</span><br><span class="line">               <span class="comment">// console.log(&#x27;接收消息:&#x27; + e.data)</span></span><br><span class="line">               <span class="keyword">var</span> data = <span class="title class_">JSON</span>.<span class="title function_">parse</span>(e.<span class="property">data</span>)</span><br><span class="line">               <span class="variable language_">console</span>.<span class="title function_">log</span>(data)</span><br><span class="line">               <span class="keyword">if</span> (data.<span class="property">msg</span> !== <span class="string">&#x27;&#x27;</span>) &#123;</span><br><span class="line">                    <span class="title class_">Message</span>(&#123;</span><br><span class="line">                         <span class="attr">message</span>: data.<span class="property">msg</span>,</span><br><span class="line">                         <span class="attr">type</span>: <span class="string">&#x27;success&#x27;</span></span><br><span class="line">                    &#125;)</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="keyword">if</span> (data.<span class="property">code</span> === <span class="string">&#x27;00&#x27;</span>) &#123;</span><br><span class="line"></span><br><span class="line">               &#125;<span class="keyword">else</span> <span class="keyword">if</span> (data.<span class="property">code</span> === <span class="string">&#x27;01&#x27;</span>)&#123;</span><br><span class="line">                    <span class="variable language_">this</span>.<span class="property">sha256Attempts</span> = data.<span class="property">data</span></span><br><span class="line">               &#125;</span><br><span class="line">               <span class="comment">// messageHandle(e.data)</span></span><br><span class="line">          &#125;,</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意这里定义session的key为mine</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://cjx_0723.gitee.io">Ther</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://cjx_0723.gitee.io/2023/04/25/%E5%90%8E%E7%AB%AF/Java%E5%BC%80%E5%8F%91/Websocket%E5%AE%9E%E7%8E%B0%E5%89%8D%E5%90%8E%E7%AB%AF%E5%AE%9E%E6%97%B6%E9%80%9A%E4%BF%A1/">http://cjx_0723.gitee.io/2023/04/25/%E5%90%8E%E7%AB%AF/Java%E5%BC%80%E5%8F%91/Websocket%E5%AE%9E%E7%8E%B0%E5%89%8D%E5%90%8E%E7%AB%AF%E5%AE%9E%E6%97%B6%E9%80%9A%E4%BF%A1/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://cjx_0723.gitee.io" target="_blank">Ther的小站</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java%E5%BC%80%E5%8F%91-Vue%E5%BC%80%E5%8F%91/">Java开发 Vue开发</a></div><div class="post_share"><div class="social-share" data-image="https://w.wallhaven.cc/full/l8/wallhaven-l83o92.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/04/26/%E5%90%8E%E7%AB%AF/Java%E5%BC%80%E5%8F%91/Java%E5%BC%80%E5%8F%91%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7%E7%B1%BB%E6%B1%87%E6%80%BB/" title="Java开发常用工具类汇总"><img class="cover" src="https://w.wallhaven.cc/full/1p/wallhaven-1pd1o9.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java开发常用工具类汇总</div></div></a></div><div class="next-post pull-right"><a href="/2023/04/24/%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/Vue%E7%BD%91%E7%BB%9C%E9%85%8D%E7%BD%AE%EF%BC%88%E8%B7%A8%E5%9F%9F%EF%BC%89/" title="Vue request配置（前后端跨域）"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Vue request配置（前后端跨域）</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ther</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">31</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#WebSocket%E7%AE%80%E4%BB%8B"><span class="toc-text">WebSocket简介</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFwebsocket"><span class="toc-text">什么是websocket</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#websocket-%E5%8E%9F%E7%90%86"><span class="toc-text">websocket 原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#websocket%E4%B8%8Ehttp%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="toc-text">websocket与http的关系</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="toc-text">代码实现</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8E%E7%AB%AF%E4%BB%A3%E7%A0%81"><span class="toc-text">后端代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E7%AB%AF%E4%BB%A3%E7%A0%81"><span class="toc-text">前端代码</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/09/06/%E7%94%9F%E6%B4%BB/%E5%AD%A6%E6%A0%A1/%E7%A0%94%E4%B8%80%E9%80%89%E8%AF%BE/" title="研一选课"><img src="https://w.wallhaven.cc/full/4g/wallhaven-4gwl6q.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="研一选课"/></a><div class="content"><a class="title" href="/2023/09/06/%E7%94%9F%E6%B4%BB/%E5%AD%A6%E6%A0%A1/%E7%A0%94%E4%B8%80%E9%80%89%E8%AF%BE/" title="研一选课">研一选课</a><time datetime="2023-09-06T07:55:08.667Z" title="发表于 2023-09-06 15:55:08">2023-09-06</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/26/%E5%90%8E%E7%AB%AF/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/MIT-6.824-%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/" title="MIT-6.824-分布式系统课程笔记">MIT-6.824-分布式系统课程笔记</a><time datetime="2023-07-26T02:09:02.000Z" title="发表于 2023-07-26 10:09:02">2023-07-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/17/%E4%B8%AD%E9%97%B4%E4%BB%B6/mysql/MySQL%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%89%EF%BC%89%E2%80%94%E2%80%94%20MySQL%E9%AB%98%E7%BA%A7/" title="MySQL教程（三）—— MySQL高级"><img src="https://img1.baidu.com/it/u=950222251,316656728&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPG?w=967&amp;h=500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MySQL教程（三）—— MySQL高级"/></a><div class="content"><a class="title" href="/2023/05/17/%E4%B8%AD%E9%97%B4%E4%BB%B6/mysql/MySQL%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%89%EF%BC%89%E2%80%94%E2%80%94%20MySQL%E9%AB%98%E7%BA%A7/" title="MySQL教程（三）—— MySQL高级">MySQL教程（三）—— MySQL高级</a><time datetime="2023-05-17T12:12:30.479Z" title="发表于 2023-05-17 20:12:30">2023-05-17</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/05/17/%E5%89%8D%E6%B2%BF%E6%8A%80%E6%9C%AF/%E5%8C%BA%E5%9D%97%E9%93%BE/%E6%AF%95%E8%AE%BE/" title="区块链毕设">区块链毕设</a><time datetime="2023-05-17T08:40:58.540Z" title="发表于 2023-05-17 16:40:58">2023-05-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/15/%E4%B8%AD%E9%97%B4%E4%BB%B6/ElasticSearch/Linux%E7%B3%BB%E7%BB%9F%E4%B8%AD%E5%AE%89%E8%A3%85Elasticsearch%E5%B9%B6%E5%AE%9E%E7%8E%B0%E5%BC%80%E6%9C%BA%E8%87%AA%E5%8A%A8%E5%90%AF%E5%8A%A8/" title="Linux系统中安装Elasticsearch并实现开机自动启动"><img src="https://img1.baidu.com/it/u=950222251,316656728&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPG?w=967&amp;h=500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Linux系统中安装Elasticsearch并实现开机自动启动"/></a><div class="content"><a class="title" href="/2023/05/15/%E4%B8%AD%E9%97%B4%E4%BB%B6/ElasticSearch/Linux%E7%B3%BB%E7%BB%9F%E4%B8%AD%E5%AE%89%E8%A3%85Elasticsearch%E5%B9%B6%E5%AE%9E%E7%8E%B0%E5%BC%80%E6%9C%BA%E8%87%AA%E5%8A%A8%E5%90%AF%E5%8A%A8/" title="Linux系统中安装Elasticsearch并实现开机自动启动">Linux系统中安装Elasticsearch并实现开机自动启动</a><time datetime="2023-05-15T08:26:31.492Z" title="发表于 2023-05-15 16:26:31">2023-05-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Ther</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.1
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container').forEach(node => {
            if (node.hasAttribute('display')) {
              btf.wrap(node, 'div', { class: 'mathjax-overflow' })
            } else {
              btf.wrap(node, 'span', { class: 'mathjax-overflow' })
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typesetPromise()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/js/search/algolia.js"></script></div></body></html>